<?php

/**
 * minority actions.
 *
 * @package    erp-dnict
 * @subpackage minority
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class minorityActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $q = Doctrine_Query::create()
            ->from('Minority m')
            ->addWhere('m.is_active = ?', true);

    $this->minorities = $q->execute();
    return sfView::SUCCESS;
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->minority_id = $request->getParameter('id', null);
    $this->form = new MinorityForm();

    if ($this->minority_id) {
      $minority = Doctrine_Core::getTable('Minority')->find($this->minority_id);
      $this->form = new MinorityForm($minority);
    }

    if ($request->isMethod('post')) {
      $form_data = $request->getParameter('minority');
      $this->form->bind($form_data);
      if ($this->form->isValid()) {
        if (!$request->getParameter('id'))
          $minority = $this->form->save();
        else { // update
          $minority = Doctrine_Core::getTable('Minority')->find($request->getParameter('id'));
          if ($minority) {
            $minority->name = $form_data['name'];
            $minority->description = $form_data['description'];
            $minority->is_active = $form_data['is_active'] == 'on' ? true : false;
            $minority->save();
          }
        }
        $this->redirect('@minority_index');
      }
    }
    return sfView::SUCCESS;
  }

  public function executeRemove(sfWebRequest $request)
  {
    $minority_id = $request->getParameter('id', null);
    if ($minority_id) {
      $minority = Doctrine_Core::getTable('Minority')->find($minority_id);
      if ($minority) {
        foreach ($minority->Profiles as $profile) {
          $profile->minority_id = 0;
          $profile->save();
        }
        $minority->is_active = false;
        $minority->save();
      }
    }
    $this->redirect('@minority_index');
  }
}
